<template>
    <el-row>
        <div class="filter-container">
            <el-button class="filter-item" type="primary" @click="create({id: 0})" plain>添加菜单</el-button>
        </div>
        <el-col :xs="24" :sm="24" :md="8" v-loading="loading">
            <el-tree
                :data="treeData"
                node-key="id"
                default-expand-all
                :expand-on-click-node="false"
                class="custom-tree">
            <span class="custom-tree-node" slot-scope="{ node, data }">
            <span :class="data.status ? '' : 'color-danger'">{{ data.name }}</span>
                <span class="custom-tree-button">
                    <el-button
                        v-if="data.level < 3"
                        type="text"
                        size="mini"
                        @click="create(data)">
                    添加
                    </el-button>
                    <el-button
                        type="text"
                        size="mini"
                        @click="edit(data)">
                    编辑
                    </el-button>
                    <el-button
                        type="text"
                        size="mini"
                        @click="destroy(data.id)">
                    删除
                    </el-button>
                </span>
            </span>
            </el-tree>
        </el-col>

        <el-col :xs="24" :sm="24" :md="16" class="hidden-sm-and-down" v-loading="loading">
            <el-table
                v-loading.body="loading"
                ref="multipleTable"
                stripe
                border
                :data="tableData"
                tooltip-effect="dark"
                style="width: 100%"
                class="text-center"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="40"/>
                <el-table-column label="排序" prop="sort" width="55"/>
                <el-table-column label="编号" prop="id" width="55"/>
                <el-table-column label="上级ID" prop="pid" width="70"/>
                <el-table-column label="图标" prop="icon" width="60">
                    <template slot-scope="scope">
                        <img :src="scope.row.icon" v-if="isUrl(scope.row.icon)"/>
                        <i :class="scope.row.icon" v-else></i>
                    </template>
                </el-table-column>
                <el-table-column label="名称" prop="name" width="120"/>
                <el-table-column label="权限" prop="access_id">
                    <template slot-scope="scope">
                        {{ scope.row.access_id ? scope.row.role_access.name : '-' }}
                    </template>
                </el-table-column>
                <el-table-column label="URL" prop="url"/>
                <el-table-column label="状态" prop="status" width="60">
                    <template slot-scope="scope">
                        <boolean-icon :data="scope.row.status"></boolean-icon>
                    </template>
                </el-table-column>
                <el-table-column label="更新时间" prop="updated_at" width="160"/>
                <el-table-column label="操 作" width="150">
                    <template slot-scope="scope">
                        <el-button

                            type="primary"
                            @click="edit(scope.row)">
                            编辑
                        </el-button>
                        <destroy-confirm
                                route="menu/Destroy"
                                :primary="scope.row.id"
                                @success="handleSearch">
                        </destroy-confirm>
                    </template>
                </el-table-column>
            </el-table>
        </el-col>

        <el-dialog
            :title="(form.id ? '编辑' : '添加')"
            :visible.sync="form.show"
            :close-on-click-modal="false"
            width="30%"
            center>
            <el-form :model="form.data"  label-width="100px">
                <el-form-item label="上级ID">
                    <el-select v-model="form.data.pid" clearable class="filter-item" placeholder="选择上级菜单">
                        <el-option label="顶级菜单" :value="0"></el-option>
                        <el-option
                            v-for="(menu, index) in topLevelMenus"
                            :key="index"
                            :label="menu.name"
                            :value="menu.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="名称">
                    <el-input v-model="form.data.name" autocomplete="off"></el-input>
                </el-form-item>
                <!--                <el-form-item label="路由">-->
                <!--                    <el-input v-model="form.data.route" :disabled="Boolean(form.data.url)" autocomplete="off"></el-input>-->
                <!--                </el-form-item>-->
                <el-form-item label="URL">
                    <el-input v-model="form.data.url" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="图标">
                    <el-input v-model="form.data.icon" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="排序">
                    <el-input-number v-model="form.data.sort" :min="0" :max="255" label="数字越大越靠前"></el-input-number>
                </el-form-item>
                <el-form-item label="状态">
                    <el-switch v-model="form.data.status" :active-value="1" :inactive-value="0"/>
                </el-form-item>
                <el-form-item label="权限">
                    <el-select v-model="form.data.access_id" :disabled="Boolean(!form.data.url)" filterable clearable class="filter-item" placeholder="选择关联权限">
                        <el-option label="请选择关联权限" :value="0"></el-option>
                        <template v-for="v in access">
                            <el-option
                                :key="v.name"
                                :label="v.name"
                                :value="v.id">
                            </el-option>
                            <template v-for="cv in v.child">
                                <el-option
                                    :key="cv.id"
                                    :label="' ---- ' + cv.name"
                                    :value="cv.id">
                                </el-option>
                            </template>
                        </template>
                    </el-select>
                </el-form-item>
                <el-form-item label="">
                    <el-button @click="form.show = false">取 消</el-button>
                    <el-button type="primary" :loading="form.loading" @click="submit">确 定</el-button>
                </el-form-item>
            </el-form>
            <!--            <div slot-cfg="footer" class="dialog-footer">-->
            <!--                -->
            <!--            </div>-->
        </el-dialog>
    </el-row>
</template>

<script>

    export default {
        data() {
            return {
                search: {
                    name: null,
                },
                loading: false,
                access: [],
                selected: [],
                tableData: [],
                pageNo: 1,
                pageSize: 200,
                //pageSizesList: [10, 15, 20, 30, 50],
                //totalDataNumber: 0,
                form: {
                    show: false,
                    loading: false,
                    data: {},
                }
            }
        },
        computed: {
            topLevelMenus() {
                let menus = [];
                for (let i in this.treeData) {
                    menus.push(Object.assign({}, this.treeData[i], {children: []}));
                    if (this.treeData[i].children) {
                        this.treeData[i].children.map(v => {
                            if (!v.url) menus.push(Object.assign({}, v, {name: '  ---   ' + v.name}));
                        });
                    }
                }
                return menus;
            },
            // todo 临时拼凑的三级菜单, 待修改
            treeData() {
                let menus = [],
                    pid = 0,
                    tableData = Object.assign({}, this.tableData);
                // 一级
                for (let i in tableData) {
                    if (tableData[i].pid === 0) {
                        menus.push(Object.assign({}, tableData[i], {level: 1, children: []}));
                        delete tableData[i];
                    }
                }
                // 二级
                for (let i in tableData) {
                    pid = tableData[i].pid;
                    for (let mi in menus) {
                        if (menus[mi].id === pid) {
                            menus[mi].children.push(Object.assign({}, tableData[i], {level: 2, children: []}));
                            delete tableData[i];
                        }
                    }
                }
                // 三级
                for (let i in tableData) {
                    pid = tableData[i].pid;
                    for (let mi in menus) {
                        for (let mci in menus[mi].children) {
                            if (menus[mi].children[mci].id === pid) {
                                menus[mi].children[mci].children.push(Object.assign({}, tableData[i], {level: 3, children: []}));
                                delete tableData[i];
                            }
                        }
                    }
                }
                return menus;
            }
        },
        methods: {
            handleSizeChange(val) {
                this.pageNo = 1;
                this.pageSize = parseInt(`${val}`);
                this.handleSearch();
            },
            handleCurrentChange(val) {
                this.pageNo = parseInt(`${val}`);
                this.handleSearch();
            },
            handleSelectionChange(val) {
                this.selected = val;
            },
            // 获取所有权限
            getAllAccess() {
                //this.accessLoading = true;
                this.$store.dispatch('roleAccess/Format').then(res => {
                    this.access = res.data.data;
                }).finally(() => {
                    //this.accessLoading = false;
                });
            },
            handleSearch() {
                this.loading = true;
                let filter = Object.assign({}, this.search, {
                    page: this.pageNo,
                    pageSize: this.pageSize,
                });
                this.$store.dispatch('menu/Lists', filter).then(res => {
                    this.tableData = res.data.data;
                    this.totalDataNumber = res.data.meta.total;
                }).finally(() => {
                    this.loading = false;
                });
            },
            initData() {
                this.handleSearch();
                this.getAllAccess();
            },
            create(row) {
                this.form.data = {
                    pid: row.id,
                }
                this.form.show = true;
            },
            edit(row) {
                this.form.data = this.$helper.deepClone(row);
                this.form.show = true;
            },
            destroy(id) {
                this.$confirm('删除后将无法恢复, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.loading = true;
                    this.$store.dispatch('menu/Destroy', id).then(res => {
                        this.$message.success('删除成功!');
                        this.handleSearch();

                        // 更新菜单缓存
                        this.$store.dispatch('backend/Menu');
                    }).finally(() => {
                        this.loading = false;
                    });
                });
            },
            getFormAction() {
                return this.form.data.id ? 'menu/Update' : 'menu/Store';
            },
            submit() {
                this.form.loading = true;
                this.$store.dispatch(this.getFormAction(), this.form.data).then(() => {
                    this.$message.success('操作成功');
                    this.handleSearch();
                    this.form.show = false;

                    // 更新菜单缓存
                    this.$store.dispatch('backend/Menu');
                }).finally(() => {
                    this.form.loading = false;
                })
            },
            isUrl(str) {
                if (str.substr(0, 1) === '/') return true;
                if (str.substr(0, 4) === 'http') return true;
                return false;
            }
        },
        created() {
            this.initData();
            //console.log(this.axios.defaults.baseURL)
        }
    }
</script>

<style lang="scss" scoped>
    .custom-tree {
        .el-tree-node {
            padding: 5px 0;
        }
        .custom-tree-button {
            margin-left: 10px;
        }
    }
</style>
